class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class InvertBinaryTree {
    public static TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        TreeNode tool = root.left;
        root.left = root.right;
        root.right = tool;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    // 辅助方法：用于前序遍历打印二叉树
    public static void preOrderPrint(TreeNode root) {
        if (root == null) {
            System.out.print("null ");
            return;
        }
        System.out.print(root.val + " ");
        preOrderPrint(root.left);
        preOrderPrint(root.right);
    }

    public static void main(String[] args) {
        // 构建测试用的二叉树 [4,2,7,1,3,6,9]
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(7);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(9);

        System.out.println("原始二叉树的前序遍历:");
        preOrderPrint(root);
        System.out.println();

        TreeNode invertedRoot = invertTree(root);

        System.out.println("反转后二叉树的前序遍历:");
        preOrderPrint(invertedRoot);
        System.out.println();
    }
}